package com.smartcruise.util.customView;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.smartcruise.R;


/**
 * Created by FengChaoQun
 * on 2018/1/21
 * 倒计时view
 */
public class TimeCountView extends View {

    private Paint paint = new Paint();
    private int currentTime;  //当前读秒
    private int totalTime;  //总秒数
    private String title;   //圆圈中主文本
    private String subTitle;  //圆圈中副文本

    private int backCircleColor;  //背景圆环颜色
    private int frontCircleColor; //前景圆环颜色
    private int titleTextColor;       //圆圈中主文本字体颜色
    private int subTitleTextColor;        //圆圈中副文本字体颜色

    private int centerX, centerY, radios;

    private float circleStrokeWidth; //圆环宽度
    private float textPadding;       //主文本和副文本间隔
    private float titleTextSize;     //主文本字体大小
    private float subTitleTextSize;  //副文本字体大小

    private ValueAnimator animator;
    private TimeCountCallBack timeCountCallBack;

    public TimeCountView(Context context) {
        super(context);
        init(context, null);
    }

    public TimeCountView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public TimeCountView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        paint.setAntiAlias(true);
        if (attrs == null) {
            return;
        }
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TimeCountView);
        totalTime = array.getInteger(R.styleable.TimeCountView_totalTime, 5000);
        subTitle = array.getString(R.styleable.TimeCountView_subTitle);
        backCircleColor = array.getColor(R.styleable.TimeCountView_backCircleColor, Color.GRAY);
        frontCircleColor = array.getColor(R.styleable.TimeCountView_frontCircleColor, Color.GREEN);
        titleTextColor = array.getColor(R.styleable.TimeCountView_titleTextColor, Color.BLACK);
        subTitleTextColor = array.getColor(R.styleable.TimeCountView_subTitleTextColor, Color.BLACK);
        circleStrokeWidth = array.getDimension(R.styleable.TimeCountView_circleStrokeWidth, 10);
        textPadding = array.getDimension(R.styleable.TimeCountView_textPadding, 10);
        titleTextSize = array.getDimension(R.styleable.TimeCountView_titleTextSize, 78);
        subTitleTextSize = array.getDimension(R.styleable.TimeCountView_subTitleTextSize, 40);
        array.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        calculateValues();
        drawCircles(canvas);
        drawText(canvas);
    }

    private void calculateValues() {
        final int paddingLeft = getPaddingLeft();
        final int paddingRight = getPaddingRight();
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();
        final int width = getWidth() - paddingLeft - paddingRight;
        final int height = getHeight() - paddingTop - paddingBottom;
        radios = Math.min(width / 2, height / 2) - (int) circleStrokeWidth;
        centerX = width / 2;
        centerY = height / 2;
    }

    private void drawCircles(Canvas canvas) {
        RectF rectF = new RectF(centerX - radios, centerY - radios, centerX + radios, centerY + radios);
        paint.setColor(backCircleColor);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(circleStrokeWidth);
        canvas.drawArc(rectF, 0, 360, false, paint);
        if (currentTime > 0) {
            paint.setColor(frontCircleColor);
            final float degree = 360 * (currentTime / (float) totalTime);
            canvas.drawArc(rectF, -90, degree, false, paint);
        }
    }

    private void drawText(Canvas canvas) {
        //将剩余时间绘制出来
        paint.setFakeBoldText(true);
        paint.setColor(titleTextColor);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(titleTextSize);
        paint.setTextAlign(Paint.Align.CENTER);
        String showTitle = String.format(getResources().getString(R.string.timeCountFormat), String.valueOf((totalTime - currentTime) / 1000 + 1));
        canvas.drawText(showTitle, centerX, centerY, paint);

        //通过asent将分数说明画在圆的下半 居中
        paint.setColor(subTitleTextColor);
        paint.setTextSize(subTitleTextSize);
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        final float asentY = centerY + textPadding;
        final float baseY = asentY - fontMetrics.ascent;
        canvas.drawText(subTitle, centerX, baseY, paint);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        startAnimation();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (animator != null && animator.isRunning()) {
            animator.pause();
        }
    }

    public void startAnimation() {
        if (animator != null && animator.isRunning()) {
            animator.cancel();
        }
        //分数无效
        if (totalTime < 0) {
            return;
        }
        animator = ValueAnimator.ofInt(0, totalTime);
        animator.setDuration(totalTime);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                currentTime = (int) animation.getAnimatedValue();
                invalidate();
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (timeCountCallBack != null) {
                    timeCountCallBack.onTimeEnd();
                }
                Log.d("TimeCountView", "animate end");
            }
        });
        animator.start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(400, 400);
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(400, heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSpecSize, 400);
        }
    }

    public int getCurrentTime() {
        return currentTime;
    }

    public void setCurrentTime(int currentTime) {
        this.currentTime = currentTime;
    }

    public int getTotalTime() {
        return totalTime;
    }

    public void setTotalTime(int totalTime) {
        this.totalTime = totalTime;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }

    public int getBackCircleColor() {
        return backCircleColor;
    }

    public void setBackCircleColor(int backCircleColor) {
        this.backCircleColor = backCircleColor;
    }

    public int getFrontCircleColor() {
        return frontCircleColor;
    }

    public void setFrontCircleColor(int frontCircleColor) {
        this.frontCircleColor = frontCircleColor;
    }

    public int getTitleTextColor() {
        return titleTextColor;
    }

    public void setTitleTextColor(int titleTextColor) {
        this.titleTextColor = titleTextColor;
    }

    public int getSubTitleTextColor() {
        return subTitleTextColor;
    }

    public void setSubTitleTextColor(int subTitleTextColor) {
        this.subTitleTextColor = subTitleTextColor;
    }

    public float getCircleStrokeWidth() {
        return circleStrokeWidth;
    }

    public void setCircleStrokeWidth(float circleStrokeWidth) {
        this.circleStrokeWidth = circleStrokeWidth;
    }

    public float getTextPadding() {
        return textPadding;
    }

    public void setTextPadding(float textPadding) {
        this.textPadding = textPadding;
    }

    public float getTitleTextSize() {
        return titleTextSize;
    }

    public void setTitleTextSize(float titleTextSize) {
        this.titleTextSize = titleTextSize;
    }

    public float getSubTitleTextSize() {
        return subTitleTextSize;
    }

    public void setSubTitleTextSize(float subTitleTextSize) {
        this.subTitleTextSize = subTitleTextSize;
    }

    public TimeCountCallBack getTimeCountCallBack() {
        return timeCountCallBack;
    }

    public void setTimeCountCallBack(TimeCountCallBack timeCountCallBack) {
        this.timeCountCallBack = timeCountCallBack;
    }

    public interface TimeCountCallBack {
        void onTimeEnd();
    }
}
